using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using EventTraceLogger.Extensions;
using System.Security.Claims;
using EventTraceLogger.Commom.Params;
using log4net;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace EventTraceLogger.Controllers
{
    [Route("log/[controller]")]
    [ApiController]
    public class LoggerController : ControllerBase
    {
        private readonly ILogger _logger;
        private static Dictionary<string, string> _dic = new Dictionary<string, string>() 
        {
            { LoggerConst.TraceId, string.Empty },
            { LoggerConst.TenantDomain, string.Empty },
            { LoggerConst.UserId, string.Empty }
        };
        public LoggerController(ILoggerFactory factory)
        {
            _logger = factory.CreateLogger(LoggerConst.Default);
        }
        [HttpPost]
        public void Post([FromForm] string? model, [FromForm] string? page, [FromForm] string? uuid,
            [FromForm] string? actions, [FromForm] string? information, [FromForm] string? ts,
            [FromForm] string? serviceId,
            [FromForm] string? token)
        {
            //获取jwt的标准方法
            //var bearToken = Request.Headers.Authorization;
            //过渡从payload中获取jwt
            //TODO：后续确定后，把下面一行修改

            try
            {
                if (!string.IsNullOrEmpty(token) && token.Length > 6)
                {
                    var bearToken = token.Substring(6).Trim();
                    var claimStr = Jose.JWT.Decode(bearToken, LoggerConst.PrivateKey);
                    var claim = JsonConvert.DeserializeObject<ClaimJwt>(claimStr);
                    _dic[LoggerConst.UserId] = string.IsNullOrEmpty(claim.sub) ? string.Empty : claim.sub;
                    _dic[LoggerConst.TenantDomain] = string.IsNullOrEmpty(claim.user_domain) ? string.Empty : claim.user_domain;
                    _dic[LoggerConst.TraceId] = Guid.NewGuid().ToString();
                }
            }
            catch
            {
                
            }
            var obj = new Data()
            {
                model = model,
                page = page,
                actions = string.IsNullOrEmpty(actions) ? null : JsonConvert.DeserializeObject<List<ActionsInformation>>(actions),
                information = string.IsNullOrEmpty(information) ? null : JsonConvert.DeserializeObject<PageInformation>(information),
                ts = ts,
                serviceId = serviceId
            };
            using (var scope = _logger.BeginScope(_dic)) { }
                _logger.LogInformation(JsonConvert.SerializeObject(obj));

        }
        //[HttpPost]
        //public void Post([FromBody] LoggerDto v)
        //{

        //}
        [Serializable]
        public class ClaimJwt
        {
            public string? sub;
            public string? user_domain;
        }
        [Serializable]
        public class Data
        {
            /// <summary>
            /// 页面信息
            /// </summary>
            public PageInformation? information;
            /// <summary>
            /// 动作/事件信息
            /// </summary>
            public List<ActionsInformation>? actions;
            /// <summary>
            /// 页面
            /// </summary>
            public string? page;
            /// <summary>
            /// 跳入时间戳
            /// </summary>
            public string? ts;
            /// <summary>
            /// 模块
            /// </summary>
            public string? model;
            /// <summary>
            /// 服务标志
            /// </summary>
            public string? serviceId;
        } 
    }
}
